#include "musicwindow.h"
#include "ui_musicwindow.h"
#include <QDebug>
#include <QMediaPlayer>
#include <QMediaContent>
#include <QFileDialog>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QTextStream>
#include <QRegExp>
#include <QStyle>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

MusicWindow::MusicWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MusicWindow)
{
    ui->setupUi(this);
    
    // 设置歌词标签的样式
    ui->label_musiclrc->setAlignment(Qt::AlignCenter);
    ui->label_musiclrc->setStyleSheet("QLabel { color: #333333; font-size: 16px; }");
    ui->label_musiclrc->setText("等待播放...");  // 设置初始文本
    
    //设置播放按钮mode=pause
    ui->btn_play->setProperty("mode","pause");
    //播放音乐
    this->player=new QMediaPlayer();
    //创建播放列表
    this->playlist=new QMediaPlaylist;

    //在线播放音乐
    this->onlineplayer=new QMediaPlayer();
    //创建在线播放列表
    this->onlineplaylist=new QMediaPlaylist;

    //创建播放模式
    this->playlist->setPlaybackMode(QMediaPlaylist::Loop);
    //播放列表添加个播放对象
    this->player->setPlaylist(playlist);

    //创建在线播放模式
    this->onlineplaylist->setPlaybackMode(QMediaPlaylist::Loop);
    //在线播放列表添加个播放对象
    this->onlineplayer->setPlaylist(onlineplaylist);

    //计算进度条进度
    connect(this->player,&QMediaPlayer::durationChanged,this,&MusicWindow::setTotal);
    connect(this->player,&QMediaPlayer::positionChanged,this,&MusicWindow::setPosition);
    connect(this->onlineplayer,&QMediaPlayer::durationChanged,this,&MusicWindow::setTotal);
    connect(this->onlineplayer,&QMediaPlayer::positionChanged,this,&MusicWindow::setPosition);

    //创建数据库链接
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("D:\\VM share\\qt\\carStytem\\SQLite\\car.db");
    if(!db.open()){
        qDebug()<<"数据库打开失败";
    }
    LocalMusicDatabase();

    // 创建网络管理器
    this->networkManager = new QNetworkAccessManager(this);
}

MusicWindow::~MusicWindow()
{
    delete ui;
}

void MusicWindow::updateBtnMode()
{
    QString mode=ui->btn_play->property("mode").toString();
    if(mode=="pause"){
        ui->btn_play->setProperty("mode","play");
        //先卸载这个按钮
        ui->btn_play->style()->unpolish(ui->btn_play);
        //重新安装
        ui->btn_play->style()->polish(ui->btn_play);
        //调用安装后的
        ui->btn_play->update();
    }
}

void MusicWindow::LocalMusicDatabase()
{
    QSqlQuery query("SELECT title, author, path, lrcpath FROM music_local");
    while (query.next()) {
        QString title = query.value(0).toString();
        QString author = query.value(1).toString();
        QString path = query.value(2).toString();
        QString lrcpath = query.value(3).toString();
        ui->localList->addItem(title + "-" + author);
        this->playlist->addMedia(QMediaContent(QUrl::fromLocalFile(path)));
    }
}

void MusicWindow::init()
{
    //获取在线音乐列表
    QNetworkAccessManager *manager=new QNetworkAccessManager;
    manager->get(QNetworkRequest(QUrl("http://localhost/music.json")));
    connect(manager,&QNetworkAccessManager::finished,this,&MusicWindow::onlineMusicShow);
}

void MusicWindow::on_btn_play_clicked()
{
    QString mode=ui->btn_play->property("mode").toString();
    if(mode=="pause"){
        ui->btn_play->setProperty("mode", "play");

        // 检查当前播放的是本地音乐还是在线音乐
        if (this->playlist->currentIndex() != -1) {
        // 播放本地音乐
            this->player->play();
            this->onlineplayer->pause(); // 暂停在线音乐
        } else if (this->onlineplaylist->currentIndex() != -1) {
            // 播放在线音乐
            this->onlineplayer->play();
            this->player->pause(); // 暂停本地音乐
        }
    }else{
        ui->btn_play->setProperty("mode","pause");
        this->player->pause();
        this->onlineplayer->pause();
    }
    //先卸载这个按钮
    ui->btn_play->style()->unpolish(ui->btn_play);
    //重新安装
    ui->btn_play->style()->polish(ui->btn_play);
    //调用安装后的
    ui->btn_play->update();
}


void MusicWindow::on_btn_load_clicked()
{
    QSqlQuery query;
    // 选择音乐文件
    QStringList musicFiles = QFileDialog::getOpenFileNames(this, tr("选择音乐"), tr("C:\\Users\\ASUS\\Desktop\\music\\music"), tr("*.mp3"));
    
    if(!musicFiles.isEmpty()) {
        // 选择对应的歌词文件
        QStringList lrcFiles = QFileDialog::getOpenFileNames(this, tr("选择歌词"), tr("D:\\nginx-1.24.0\\nginx-1.24.0\\html\\musiclrc"), tr("*.lrc"));
        
        for(int i = 0; i < musicFiles.size(); i++) {
            QFileInfo musicInfo(musicFiles[i]);
            QString lrcPath = (i < lrcFiles.size()) ? lrcFiles[i] : "";
            
            ui->localList->addItem(musicInfo.fileName());
            this->playlist->addMedia(QMediaContent(QUrl::fromLocalFile(musicFiles[i])));
            
            // 将文件信息存入数据库
            QString sql = QString("INSERT INTO music_local (title, author, path, lrcpath) VALUES ('%1','%2','%3','%4')")
                    .arg(musicInfo.fileName())
                    .arg("未知")
                    .arg(musicFiles[i])
                    .arg(lrcPath);
            
            if(!query.exec(sql)) {
                qDebug() << "添加失败" << query.lastError();
            }
        }
    }
}


void MusicWindow::on_localList_itemDoubleClicked(QListWidgetItem *item)
{
    int index = ui->localList->currentRow();
    this->playlist->setCurrentIndex(index);
    
    // 从数据库获取歌词路径
    QSqlQuery query;
    QString fullText = item->text();  // 获取完整的文本
    // 移除 "-未知" 部分
    fullText = fullText.left(fullText.lastIndexOf("-"));
    qDebug() << "完整文本:" << fullText;
    
    // 修改查询语句，只使用标题
    QString title = fullText;
    query.prepare("SELECT lrcpath FROM music_local WHERE title = ?");
    query.addBindValue(title);
    qDebug() << "查询参数 - 标题:" << title;
    
    if(query.exec()) {
        qDebug() << "SQL语句:" << query.lastQuery();
        if(query.next()) {
            QString lrcPath = query.value(0).toString();
            qDebug() << "获取到歌词路径:" << lrcPath;
            if(!lrcPath.isEmpty()) {
                loadLyrics(lrcPath);
            } else {
                ui->label_musiclrc->setText("暂无歌词");
            }
        } else {
            qDebug() << "未找到匹配的记录";
            ui->label_musiclrc->setText("暂无歌词");
        }
    } else {
        qDebug() << "查询执行失败:" << query.lastError().text();
        ui->label_musiclrc->setText("歌词加载失败");
    }
    
    this->player->play();
    this->updateBtnMode();
}

void MusicWindow::loadLyrics(const QString &path)
{
    lyrics.clear();
    QFile file(path);
    
    qDebug() << "尝试加载歌词文件:" << path;
    
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开歌词文件:" << path << ", 错误:" << file.errorString();  // 添加错误信息
        ui->label_musiclrc->setText("暂无歌词");
        return;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    QByteArray data = in.readAll().toUtf8();
    qDebug() << "歌词文件内容长度:" << data.length();  // 添加调试输出
    parseLyrics(data);
    file.close();
}

void MusicWindow::parseLyrics(const QByteArray &data)
{
    QRegExp rx("\\[(\\d+):(\\d+\\.\\d+)\\](.*)");
    QStringList lines = QString(data).split("\n");
    qDebug() << "歌词行数:" << lines.size();  // 添加调试输出
    
    for (const QString &line : lines) {
        if (rx.indexIn(line) != -1) {
            int minutes = rx.cap(1).toInt();
            double seconds = rx.cap(2).toDouble();
            QString text = rx.cap(3);
            qint64 timestamp = (minutes * 60 + seconds) * 1000;
            lyrics[timestamp] = text;
            qDebug() << "解析歌词:" << minutes << ":" << seconds << " -> " << text;
        } else {
            qDebug() << "无法解析行:" << line;  // 添加调试输出
        }
    }
    
    qDebug() << "解析完成，歌词数量:" << lyrics.size();  // 添加调试输出
    
    if (lyrics.isEmpty()) {
        ui->label_musiclrc->setText("暂无歌词");
    } else {
        ui->label_musiclrc->setText(lyrics.begin().value());
    }
}

void MusicWindow::updateLyric(qint64 position)
{
    if (lyrics.isEmpty()) {
        return;
    }

    try {
        qDebug() << "当前播放位置:" << position;
        qDebug() << "歌词数量:" << lyrics.size();

        // 找到当前时间最接近的歌词
        QMap<qint64, QString>::const_iterator it = lyrics.lowerBound(position);
        
        // 如果找不到合适的歌词，显示最后一句
        if (it == lyrics.end()) {
            if (!lyrics.isEmpty()) {
                auto lastLyric = lyrics.end();
                --lastLyric;
                ui->label_musiclrc->setText(lastLyric.value());
                qDebug() << "显示最后一句歌词:" << lastLyric.value();
            }
            return;
        }

        // 如果是第一句歌词
        if (it == lyrics.begin()) {
            ui->label_musiclrc->setText(it.value());
            qDebug() << "显示第一句歌词:" << it.value();
            return;
        }

        // 显示当前时间之前的最近一句歌词
        --it;
        ui->label_musiclrc->setText(it.value());
        qDebug() << "显示当前歌词:" << it.value();

    } catch (const std::exception& e) {
        qDebug() << "更新歌词时发生错误:" << e.what();
        ui->label_musiclrc->setText("歌词显示错误");
    } catch (...) {
        qDebug() << "更新歌词时发生未知错误";
        ui->label_musiclrc->setText("歌词显示错误");
    }
}

void MusicWindow::on_btn_next_clicked()
{
    int index = this->playlist->currentIndex();
    if(index == this->playlist->mediaCount()-1){
        index = 0;
    }else{
        index++;
    }
    this->playlist->setCurrentIndex(index);
    ui->localList->setCurrentRow(index);
    
    // 加载新歌词
    QListWidgetItem* item = ui->localList->item(index);
    if (item) {
        QSqlQuery query;
        QString fullText = item->text();
        fullText = fullText.left(fullText.lastIndexOf("-"));  // 移除 "-未知" 部分
        query.prepare("SELECT lrcpath FROM music_local WHERE title = ?");
        query.addBindValue(fullText);  // 不需要添加 .mp3 后缀
        
        if(query.exec() && query.next()) {
            QString lrcPath = query.value(0).toString();
            if(!lrcPath.isEmpty()) {
                loadLyrics(lrcPath);
            } else {
                ui->label_musiclrc->setText("暂无歌词");
            }
        }
    }
    
    this->player->play();

    // 在线音乐部分
    int indexonline = this->onlineplaylist->currentIndex();
    if(indexonline == this->onlineplaylist->mediaCount()-1){
        indexonline = 0;
    }else{
        indexonline++;
    }
    this->onlineplaylist->setCurrentIndex(indexonline);
    ui->onlineList->setCurrentRow(indexonline);
    
    // 加载在线歌词
    QListWidgetItem* onlineItem = ui->onlineList->item(indexonline);
    if (onlineItem) {
        QString fullText = onlineItem->text();
        QString lrcPath = onlineLrcPaths.value(fullText);
        if (!lrcPath.isEmpty()) {
            qDebug() << "在线歌词路径:" << lrcPath;
            if (lrcPath.startsWith("http")) {
                loadOnlineLyrics(lrcPath);  // 使用新的函数加载在线歌词
            } else {
                loadLyrics(lrcPath);        // 本地歌词仍使用原来的函数
            }
        } else {
            qDebug() << "未找到在线歌词";
            ui->label_musiclrc->setText("暂无歌词");
        }
    }
    
    this->onlineplayer->play();
    this->updateBtnMode();
}


void MusicWindow::on_btn_pre_clicked()
{
    //本地
    int index = this->playlist->currentIndex();
    if(index == 0){
        index = this->playlist->mediaCount()-1;
    }else{
        index--;
    }
    this->playlist->setCurrentIndex(index);
    ui->localList->setCurrentRow(index);
    
    // 加载新歌词
    QListWidgetItem* item = ui->localList->item(index);
    if (item) {
        QSqlQuery query;
        QString fullText = item->text();
        fullText = fullText.left(fullText.lastIndexOf("-"));
        query.prepare("SELECT lrcpath FROM music_local WHERE title = ?");
        query.addBindValue(fullText);
        
        if(query.exec() && query.next()) {
            QString lrcPath = query.value(0).toString();
            if(!lrcPath.isEmpty()) {
                loadLyrics(lrcPath);
            } else {
                ui->label_musiclrc->setText("暂无歌词");
            }
        }
    }
    
    this->player->play();

    // 在线音乐部分
    int indexonline = this->onlineplaylist->currentIndex();
    if(indexonline == 0){
        indexonline = this->onlineplaylist->mediaCount()-1;
    }else{
        indexonline--;
    }
    this->onlineplaylist->setCurrentIndex(indexonline);
    ui->onlineList->setCurrentRow(indexonline);
    
    // 加载在线歌词
    QListWidgetItem* onlineItem = ui->onlineList->item(indexonline);
    if (onlineItem) {
        QString fullText = onlineItem->text();
        QString lrcPath = onlineLrcPaths.value(fullText);
        if (!lrcPath.isEmpty()) {
            qDebug() << "在线歌词路径:" << lrcPath;
            if (lrcPath.startsWith("http")) {
                loadOnlineLyrics(lrcPath);  // 使用新的函数加载在线歌词
            } else {
                loadLyrics(lrcPath);        // 本地歌词仍使用原来的函数
            }
        } else {
            qDebug() << "未找到在线歌词";
            ui->label_musiclrc->setText("暂无歌词");
        }
    }
    
    this->onlineplayer->play();
    this->updateBtnMode();
}

void MusicWindow::setTotal(qint64 duration)
{
    this->total=duration;
}

void MusicWindow::setPosition(qint64 position)
{
    if(this->total > 0){
        int progress = position * 100 / this->total;
        ui->progress_bar->setValue(progress);
        updateLyric(position);  // 确保这行代码被调用
        qDebug() << "Progress:" << progress << "%, Position:" << position;  // 添加调试输出
    }
}

void MusicWindow::on_pushButton_clicked()
{
    this->parentWidget()->show();
    this->hide();
}


void MusicWindow::on_progress_bar_sliderReleased()
{
    int value=ui->progress_bar->value();

    //通过进度条计算播放进度
    int postion=value*this->total/100;
    this->player->setPosition(postion);
    this->onlineplayer->setPosition(postion);
}

void MusicWindow::onlineMusicShow(QNetworkReply *reply)
{
    QByteArray data = reply->readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    if (jsonDoc.isArray()) {
        QJsonArray jsonArray = jsonDoc.array();
        for (const QJsonValue &value : jsonArray) {
            if (value.isObject()) {
                QJsonObject songObject = value.toObject();
                QString songName = songObject["name"].toString();
                QString songAuthor = songObject["author"].toString();
                QString songPath = songObject["path"].toString();
                QString lrcPath = songObject["lrcpath"].toString();

                // 将歌曲信息添加到 onlineList 中
                ui->onlineList->addItem(songName + " - " + songAuthor);

                // 将歌曲路径添加到播放列表
                this->onlineplaylist->addMedia(QMediaContent(QUrl(songPath)));
                
                // 保存歌词路径到 map 中，用于后续查找
                onlineLrcPaths[songName + " - " + songAuthor] = lrcPath;
            }
        }
    }
}

void MusicWindow::loadOnlineLyrics(const QString &url)
{
    qDebug() << "开始下载在线歌词:" << url;
    QNetworkRequest request(url);
    QNetworkReply *reply = networkManager->get(request);
    
    connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();
            parseLyrics(data);
        } else {
            qDebug() << "下载歌词失败:" << reply->errorString();
            ui->label_musiclrc->setText("歌词加载失败");
        }
        reply->deleteLater();
    });
}

void MusicWindow::on_onlineList_itemDoubleClicked(QListWidgetItem *item)
{
    int index = ui->onlineList->currentRow();
    this->onlineplaylist->setCurrentIndex(index);
    
    // 加载在线歌词
    QString fullText = item->text();
    qDebug() << "在线音乐标题:" << fullText;
    
    // 从 map 中获取歌词路径
    QString lrcPath = onlineLrcPaths.value(fullText);
    if (!lrcPath.isEmpty()) {
        qDebug() << "在线歌词路径:" << lrcPath;
        if (lrcPath.startsWith("http")) {
            loadOnlineLyrics(lrcPath);  // 使用新的函数加载在线歌词
        } else {
            loadLyrics(lrcPath);        // 本地歌词仍使用原来的函数
        }
    } else {
        qDebug() << "未找到在线歌词";
        ui->label_musiclrc->setText("暂无歌词");
    }
    
    // 切换后立即播放
    this->player->pause();
    this->onlineplayer->play();
    this->updateBtnMode();
}

